from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from users.models import User
from rest_framework.utils import json

def jwt_response_payload_handler(token, user, request,**kwargs):
    """为返回的结果添加用户相关信息"""

    return {
        'token': token,
        'user_id': user.pk,
        'username': user.username,
    }

class MyAuthentication(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 根据前台提交的数据获取用户对象
        user = User.objects.filter(username=username, is_staff=True,is_active=True).first()
        # 判断用户是否存在并且密码是否正确
        if user and check_password(password, user.password):
            # 判断通过，返回用户对象
            return user
        # 用户不存在或者密码不正确时
        else:
            return None


from ronglian_sms_sdk import SmsSDK

from django.conf import settings

from p6_0518.celery import app

@app.task
def send_message(sms_code,mobile,expire=5):
    # 实例化工具对象
    sdk = SmsSDK(accId=settings.ACCID,accToken=settings.ACCTOKEN,appId=settings.APPID)
    # 准备数据
    tid = "1"
    datas = ("%s"%sms_code, "%s"%expire)
    # 发送短信
    res = sdk.sendMessage(tid=tid,mobile=mobile,datas=datas)
    print("容联云返回的响应:",res)
    # 解析json数据
    data= json.loads(res)
    # 判断发送短信是否成功
    if data.get("statusCode") == "000000":
        return True
    return False

